package com.blast.comicsisland.utils;

import android.util.Log;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.zip.GZIPInputStream;

/**
 * Created by Android Studio
 * Author: hg
 * Date: 15/6/24
 * Email: 531057892@qq.com
 */
public class JsonUtils {

    /**
     * 进行post请求
     * @param path 请求的地址，例如："http://mhjk.1391.com/comic/comicslist_v2_sb?e=" + (System.currentTimeMillis() / 1000)
     * @param jsonPath 请求体的内容，json的字符串，例如：String str = "{\"type\":\"1\",\"pageno\":1,\"pagesize\":\"10\"}";
     * @return
     */
    public static String doPostRequest(String path,String jsonPath){
        String ret = null;
        Log.d("JsonUtils","path:"+path);
        Log.d("JsonUtils","jsonPath:"+jsonPath);
        try {
            URL url = new URL(path);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();

            conn.setRequestMethod("POST");
            conn.setReadTimeout(5000);
            conn.setDoInput(true);
            conn.setDoOutput(true);

            //拼接post请求的请求头
            conn.setRequestProperty("Content-Type", "application/json");

            byte[] data = jsonPath.getBytes();
            conn.setRequestProperty("content-Length", Integer.toString(data.length));
            conn.setRequestProperty("Host","mhjk.1391.com");
            conn.setRequestProperty("connection", "Keep-alive");
            conn.setRequestProperty("User-Agent", "Mozilla/5.0(Linux;U;Android 2.2.1;en-us;Nexus One Build.FRG83)" +
                    "AppleWebKit/553.1(KHTML,like Gecko) Version/4.0 Mobile Safari/533.1 Paros/3.2.13");



            //开启链接
            conn.connect();

            //发送post请求的请求体
            OutputStream outputStream = conn.getOutputStream();
            outputStream.write(data);
            outputStream.close();

            //读取返回的数据
            int code = conn.getResponseCode();
            InputStream inputStream = conn.getInputStream();
            if (inputStream != null) {

                String contentEncoding = conn.getContentEncoding();
                if ("gzip".equals(contentEncoding)) {
                    inputStream = new GZIPInputStream(inputStream);
                }


                ret = getJsonString(inputStream);
                conn.disconnect();
            }
            Log.d("JsonUtils","code:"+code+"ret:"+ret);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return ret;
    }

    /**
     * 进行get请求
     * @param path get请求的地址,例如：String str = "http://mhjk.1391.com/comic/getproad?adgroupid=9&e="+(System.currentTimeMillis()/1000)+"&platformtype=1&channelid=baidu";
     * @return
     */
    public static String doGetRequest(String path){
        String ret = null;

        try {
            URL url = new URL(path);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();

            conn.setRequestMethod("GET");
            conn.setDoInput(true);
            conn.setReadTimeout(5000);

            conn.connect();

            int responseCode = conn.getResponseCode();

            if (responseCode == 200 ){
                InputStream in = conn.getInputStream();

                ret = getJsonString(in);
                conn.disconnect();
            }
            Log.d("JsonUtils","code:"+responseCode+",ret:"+ret);

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }


        return ret;
    }


    /**
     * 对发送的json字符串进行URL编码
     * @param str json字符串
     * @return
     */
    public static String doURLEncoder(String str){
        String ret = null;
        if (str != null) {
            ret = URLEncoder.encode(str);
        }
        return ret;
    }

    /**
     * 将返回的Stream转化为字符串
     * @param inputStream
     * @return
     * @throws java.io.IOException
     */
    private static String getJsonString(InputStream inputStream) throws IOException {
        String ret = null;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();

        byte[] arr = new byte[1024];
        int len;
        while ((len = inputStream.read(arr)) != -1) {
            bos.write(arr, 0, len);
        }

        arr = bos.toByteArray();

        ret = new String(arr, "UTF-8");

        bos.close();

        arr = null;

        Log.d("MainActivity", "json:" + ret);
        return ret;
    }


    public static String stringToRegex(String str){
        String ret = null;
        if (str != null) {
            ret = str.replaceAll("\\\\", "").replaceAll("\"\\[","[").replaceAll("]\"","]");
        }
        return ret;
    }

}
